import React, {useEffect, useState} from 'react'
import {Form, Button, InputNumber,Input, Modal, Row, Col, message, Divider} from 'antd'
import {connect} from 'umi'
import { getScoreWeightsInfo, getScoreProgramAndTopic, getScoreTopicList, saveSoreProgramTopic, saveAndUpdateScoreTopicInfo } from '../../service'

const FormItem = Form.Item;

const formLayout = {
  labelCol: {span: 7},
};

const UpdateForm = (props) => {

  const {visible, onSubmit, onCancel, current} = props;
  const [form] = Form.useForm();
  const [topicList,setTopicList] = useState([])
  const [loading,setLoading] = useState(false)

  useEffect(  () => {
    if (visible && current){
      init()
    }
  }, [visible]);

  const init = async ()=>{
    getScoreWeightsInfo(current.weightsId).then(res =>{
      form.setFieldsValue(res);
    })
    const ids = await getScoreProgramAndTopic(current.id)
    const topicList = await getScoreTopicList(current.id)
    const list = ids.map((item)=>{
      return topicList.find((topic)=>item.topicId === topic.id)
    })
    setTopicList(list)
    list.forEach((item,index)=>{
      form.setFieldsValue({[`topic${index}`]:item?.title});
    })
  }

  const onFormCancel = () => {
    onCancel();
    form.resetFields();
  };

  const onFinish = async () => {
    form.validateFields().then( async r => {
      setLoading(true)
      let fieldsValue = form.getFieldsValue();
      let sumScore = 0;
      let id = current ? current.id : null;
      sumScore += fieldsValue.superiorWeights
      sumScore += fieldsValue.sameLevelWeights
      sumScore += fieldsValue.subordinateWeights
      sumScore += fieldsValue.myWeights
      if (sumScore!==100){
        message.error('权重合计需为100%!');
        setLoading(false);
        return;
      }
      // return
      if(topicList.length > 0) {
        // 已经有题目
        topicList.forEach((item,index)=>{
          if(item.title !== fieldsValue[`topic${index}`]) {
            saveAndUpdateScoreTopicInfo({
              ...item, title:fieldsValue[`topic${index}`]
            })
          }
        })
      } else {
        // 还没有设置，需要绑定
        let list = [0,1,2,3,4,5,6,7,8,9]
        for(let i=0;i<10;i++) {
          let res = await saveAndUpdateScoreTopicInfo({
            title:fieldsValue[`topic${i}`],
            type: 0,
            maxScore: 10
          })
          list[i] = res?.data
        }
        await saveSoreProgramTopic({
          scoreProgramTopicVoArrayList:list.map((item,index)=>{
            return {
              programId: id,
              topicId: item
            }
          })
        })
      }
      onSubmit({ id:current.weightsId,
        superiorWeights:fieldsValue.superiorWeights,
        sameLevelWeights:fieldsValue.sameLevelWeights,
        subordinateWeights:fieldsValue.subordinateWeights,
        myWeights:fieldsValue.myWeights,
      });
      form.resetFields();
      setLoading(false)
    });
  };


  const renderContent = () => {
    return (
      <>
        <Row gutter={24} justify='center' style={{ background: '#ffffff'}}>
          <Col span={12} style={{display: 'flex'}}>
            <FormItem label="上级权重：" style={{width: '80%'}} name='superiorWeights' validateFirst={true}
                       rules={[{required: true, message: '上级权重不能为空！'}]}>
              <InputNumber style={{width: '100%'}} placeholder="请输入" max={100} min={0}/>
            </FormItem>
            <FormItem>
              <span style={{padding: '10px', width: '20%'}}>%</span>
            </FormItem>
          </Col>
          <Col span={12} style={{display: 'flex'}}>
            <FormItem label="同级权重：" style={{width: '80%'}} name='sameLevelWeights' validateFirst={true}
                       rules={[{required: true, message: '同级权重不能为空！'}]}>
              <InputNumber style={{width: '100%'}} placeholder="请输入" max={100} min={0}/>
            </FormItem>
            <FormItem>
              <span style={{padding: '10px', width: '20%'}}>%</span>
            </FormItem>
          </Col>
          <Col span={12} style={{display: 'flex'}}>
            <FormItem label="下级权重：" style={{width: '80%'}} name='subordinateWeights' validateFirst={true}
                       rules={[{required: true, message: '下级权重不能为空！'}]}>
              <InputNumber style={{width: '100%'}} placeholder="请输入" max={100} min={0}/>
            </FormItem>
            <FormItem>
              <span style={{padding: '10px', width: '20%'}}>%</span>
            </FormItem>
          </Col>
          <Col span={12} style={{display: 'flex'}}>
            <FormItem label="自评权重：" style={{width: '80%'}} name='myWeights' validateFirst={true}
                       rules={[{required: true, message: '自评权重不能为空！'}]}>
              <InputNumber style={{width: '100%'}} placeholder="请输入" max={100} min={0}/>
            </FormItem>
            <FormItem>
              <span style={{padding: '10px', width: '20%'}}>%</span>
            </FormItem>
          </Col>
        </Row>

        <Divider>题目设置</Divider>

        <Row gutter={24} style={{background: '#ffffff'}}>

          {
            [1,2,3,4,5,6,7,8,9,10].map((item,index)=>{
              return <Col key={index} span={24} style={{display: 'flex'}}>
                <FormItem label={`题目${index+1}：`} style={{width: '80%'}} name={`topic${index}`} validateFirst={true}
                          rules={[{required: true, message: '题目不能为空！'}]}>
                  <Input style={{width: '100%'}} placeholder="请输入" />
                </FormItem>
              </Col>
            })
          }
        </Row>
      </>
    )
  };

  const renderFooter = () => {
    return (
      <>
        <Button onClick={() => onFormCancel()}>取消</Button>
        <Button type="primary" onClick={() => onFinish()} loading={loading}>保存</Button>
      </>
    )
  };

  return (
    <Modal
      width='70%'
      destroyOnClose
      title={`${current && current.programName}评分配置`}
      visible={visible}
      footer={renderFooter()}
      onOk={onFinish}
      onCancel={onFormCancel}
      okText="确认"
      cancelText="取消"
    >
      <Form
        {...formLayout}
        form={form}
        style={{paddingTop: '24px'}}
      >
        {renderContent()}
      </Form>
    </Modal>
  )
};

export default connect(({}) => ({

}))(UpdateForm)
